#include"MainWindow.h"
#include"AddressWidget.h"
#include<QModelIndexList>
#include<QAction>
#include<QFileDialog>
#include<QMenuBar>
#include<QMenu>
#include<QItemSelection>


MainWindow::MainWindow()
{
	addressWidget_ = new AddressWidget;
	setCentralWidget(addressWidget_);
	createMenus();
	
	setWindowTitle(tr("Address Book"));
}


void MainWindow::updateActions(const QItemSelection & selection)
{
    QModelIndexList indexes = selection.indexes();

	if(!indexes.isEmpty())
	{
		removeAct_->setEnabled(true);
		editAct_->setEnabled(true);
	}else{
		removeAct_->setEnabled(false);
		editAct_->setEnabled(false);
	}
}

void MainWindow::openFile()
{
	QString fileName = QFileDialog::getOpenFileName(this);
	if(!fileName.isEmpty())
	{
		addressWidget_->readFromFile(fileName);
	}
}

void MainWindow::saveFile()
{
	QString fileName = QFileDialog::getSaveFileName(this);
	if(fileName.isEmpty())
	{
		addressWidget_->writeToFile(fileName);
	}
}


void MainWindow::createMenus()
{

	fileMenu_ = menuBar()->addMenu(tr("&File"));

	openAct_ = new QAction(tr("&Open...") , this);
	fileMenu_->addAction(openAct_);
	connect(openAct_ , &QAction::triggered , this , &MainWindow::openFile);

	saveAct_ = new QAction(tr("&Save As ...") ,this);
	fileMenu_->addAction(saveAct_);
	connect(saveAct_ , &QAction::triggered , this , &MainWindow::saveFile);
	
	fileMenu_->addSeparator();

	exitAct_ = new QAction(tr("E&xit") ,this);
	fileMenu_->addAction(exitAct_);
    connect(exitAct_ , &QAction::triggered , this , &MainWindow::QWidget::close);

	toolMenu_ = menuBar()->addMenu(tr("&Tools"));

	addAct_ = new QAction(tr("&Add Entry ...") ,this);
	toolMenu_->addAction(addAct_);
    connect(addAct_ , &QAction::triggered , addressWidget_,  &AddressWidget::showAddEntryDialog);

	editAct_ = new QAction(tr("&Edit Entry..."),this);
	editAct_->setEnabled(false);
	toolMenu_->addAction(editAct_);
	connect(editAct_ , &QAction::triggered , addressWidget_ , &AddressWidget::editEntry);

	toolMenu_->addSeparator();

	removeAct_ = new QAction(tr("&Remove Entry") ,this);
	removeAct_->setEnabled(false);
    toolMenu_->addAction(removeAct_);
	connect(removeAct_ , &QAction::triggered , addressWidget_ , &AddressWidget::removeEntry);

	connect(addressWidget_ , &AddressWidget::selectionChanged ,this ,&MainWindow::updateActions);
}

